package com.bage.wx.service.impl;

import com.bage.wx.constant.WXApiConstant;
import com.bage.wx.dto.AccessTokenResult;
import com.bage.wx.dto.MpQrCodeCreateRequest;
import com.bage.wx.dto.MpQrCodeCreateResult;
import com.bage.wx.service.WXService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

@Slf4j
@Service
@RequiredArgsConstructor
public class WXServiceImpl implements WXService {

    final WebClient webClient;

    final RedisTemplate<String, Object> redisTemplate;

    final String MP_TOKEN_REDIS_CACHE_KEY = "MP_TOKEN_REDIS_CACHE_KEY:";

    // 接口重试次数
    final int retry = 3;

    @Override
    public void setMpAccessTokenCache(String appId, String secret) {
        AccessTokenResult accessTokenResult = getMpAccessToken(appId, secret);
        redisTemplate.opsForValue().set(MP_TOKEN_REDIS_CACHE_KEY + appId, accessTokenResult);
    }

    @Override
    public AccessTokenResult getMpAccessTokenByCache(String appId) {
        return (AccessTokenResult) redisTemplate.opsForValue().get(MP_TOKEN_REDIS_CACHE_KEY + appId);
    }

    @Override
    public AccessTokenResult getMpAccessToken(String appid, String secret) {
        String url = String.format(WXApiConstant.ACCESS_TOKEN_API, appid, secret);
        return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(AccessTokenResult.class)
                .retry(retry)
                .block();
    }

    @Override
    public MpQrCodeCreateResult createMpQrcodeCreate(String token, MpQrCodeCreateRequest request) {
        String url = String.format(WXApiConstant.MP_QRCODE_CREATE, token);
        MpQrCodeCreateResult result = webClient.post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(request))
                .retrieve()
                .bodyToMono(MpQrCodeCreateResult.class)
                .retry(retry)
                .block();
        if (result == null || Strings.isBlank(result.getTicket())) {
            return result;
        }
        result.setQrCodeUrl("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + result.getTicket());
        return result;
    }
}
